var express = require('express');
var router = express.Router();
const getRawBody = require('raw-body');
const crypto = require('crypto');
const config = require('../config').wechat;
var parseXMLAsync = require('../wechat/parseXMLAsync.js');
var formatMessage = require('../wechat/formatMessage.js');
var updateOrder = require('../wechat/updateOrder.js');

///////////////////////////////////////////////////
function MD5(str) {
    let md5sum = crypto.createHash('md5');
    md5sum.update(str)
    str = md5sum.digest('hex')
    return str
}
// 根据微信回调支付结果生成
function checkSign (obj) {
    let params = []
    for (let key in obj) {
        if (key != 'sign') {
            let aLine = key + '=' + obj[key]
            params.push(aLine)
        }
    }
    let strA = params.sort().join('&')
    let stringSignTemp = strA + `&key=${config.apiCert}`
    let _sign = MD5(stringSignTemp).toUpperCase()
    if (_sign == obj.sign) {
        return true
    } else {
        return false
    }
}

// 客户端支付成功，微信发起的回调，生成签名回应接收支付成功
router.post('/', async function(req, res, next) {

        var data = await getRawBody(req, {
            length: req.headers['content-length'],
            limit: '1mb',
            encoding:req.charset
        })

        data = await parseXMLAsync(data)
        data = formatMessage(data.xml)

        if (checkSign(data)) {//对微信传来的结果作出回应

            let out_trade_no = data.out_trade_no;
            await updateOrder(out_trade_no,data)// 支付成功，修改订单支付字段

            return res.send(`
            <xml>
                <return_code><![CDATA[SUCCESS]]></return_code>
                <return_msg><![CDATA[OK]]></return_msg>
            </xml>`
            )
        } else {
            return res.send(`
            <xml>
                <return_code><![CDATA[FAIL]]></return_code>
                <return_msg><![CDATA[签名失败]]></return_msg>
            </xml>`
            )
        }

})

module.exports = router;
